import {
  Button,
  Card,
  Col,
  Drawer,
  Flex,
  Form,
  Input,
  message,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Transfer,
} from "antd";
import { useDispatch, useSelector } from "react-redux";
import {
  addRole,
  deleteRole,
  IRole,
  selectAllRoles,
  updateRole,
} from "../../../store/slices/usersSlice.ts";
import { useState } from "react";

const color = [
  { value: "blue", label: "蓝色" },
  { value: "green", label: "绿色" },
  { value: "purple", label: "紫色" },
  { value: "red", label: "红色" },
  { value: "orange", label: "橙色" },
];

export default function Role() {
  const dispatch = useDispatch();
  const [messageApi, contextHolder] = message.useMessage();
  // 所有角色
  const roles = useSelector(selectAllRoles);
  // 角色编辑Drawer
  const [editRoleDrawer, setEditRoleDrawer] = useState(false);
  // 状态
  const [editMode, setEditMode] = useState(false);
  // 当前角色
  const [currentRole, setCurrentRole] = useState<IRole>({
    label: "",
    color: "",
    value: -1,
    createTime: "",
  });

  const openEditRoleDrawer = (role: IRole | null) => {
    if (role) {
      setCurrentRole(role);
      setEditMode(true);
    }
    setEditRoleDrawer(true);
  };

  const closeEditRoleDrawer = () => {
    setEditRoleDrawer(false);
    setEditMode(false);
  };

  const DrawerExtra = () => {
    let clickHandler = () => {
      const date = new Date();
      dispatch(
        addRole({
          ...currentRole,
          value: Math.floor(Math.random() * 1000),
          createTime: `${date.getFullYear()}-${date.getDate()}-${date.getDay()}`,
        }),
      );
      closeEditRoleDrawer();
    };

    if (editMode) {
      clickHandler = () => {
        dispatch(updateRole(currentRole));
        closeEditRoleDrawer();
      };
    }

    return (
      <Space>
        <Button type="primary" onClick={clickHandler}>
          {editMode ? "修改" : "新增"}
        </Button>
        <Button onClick={closeEditRoleDrawer}>取消</Button>
      </Space>
    );
  };

  return (
    <>
      <Flex vertical={true} style={{ padding: "10px" }}>
        <Card
          title="职位列表"
          extra={
            <Space>
              <Button type="primary" onClick={() => openEditRoleDrawer(null)}>
                新增角色
              </Button>
            </Space>
          }>
          <Table dataSource={roles} rowKey="value">
            <Table.Column dataIndex="value" title="编号" />
            <Table.Column
              dataIndex="label"
              title="职位"
              render={(text, record) => <Tag color={record.color}>{text}</Tag>}
            />
            <Table.Column dataIndex="createTime" title="创建时间" />
            <Table.Column
              title="操作"
              render={(_text, record: IRole) => (
                <Space>
                  <a onClick={() => openEditRoleDrawer(record)}>编辑</a>
                  <a
                    onClick={() => {
                      // 多个用户 禁止 删除
                      messageApi
                        .error(`该职位[${record.label}]存在用户`, 5)
                        .then(() => {});
                      dispatch(deleteRole(record));
                    }}>
                    删除
                  </a>
                </Space>
              )}
            />
          </Table>
        </Card>
      </Flex>
      <Drawer
        size="large"
        closeIcon={null}
        open={editRoleDrawer}
        title={editMode ? "修改角色" : "新增角色"}
        onClose={closeEditRoleDrawer}
        afterOpenChange={(open) => {
          if (!open) {
            setCurrentRole({ label: "", color: "", value: -1, createTime: "" });
          }
        }}
        extra={<DrawerExtra />}>
        <Form>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="名称">
                <Input
                  value={currentRole.label}
                  onChange={(e) =>
                    setCurrentRole({ ...currentRole, label: e.target.value })
                  }
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="颜色">
                <Select
                  options={color}
                  value={currentRole.color}
                  optionRender={(props) => {
                    return (
                      <Tag color={props.value as string}>{props.label}</Tag>
                    );
                  }}
                  onChange={(value) => {
                    setCurrentRole({ ...currentRole, color: value });
                  }}
                />
              </Form.Item>
            </Col>
          </Row>
          <Row>
            <Col span={24}>
              <Transfer />
            </Col>
          </Row>
        </Form>
      </Drawer>
      {contextHolder}
    </>
  );
}
